import requests  
import json  
import paho.mqtt.client as mqtt  
import time
import uuid
import os
import psutil

HOST = "http://192.168.10.10:9001"

# HTTP请求地址  
STATUS_URL = HOST + "/api/robot_status"
  
# MQTT配置  
client_id = "bj00_position_publisher"  
mqtt_server = "121.5.162.11"  
mqtt_port = 1883  


TMS_HOST = "121.5.162.11"
TMS_PORT = "8081"
UUID_URL = "http://"+TMS_HOST+":"+TMS_PORT+"/robot/getUUID"


CHARGE_URL = HOST + "/api/move?marker=charge_point_3F_1"

go_charge_count = 0

def go_charge():
    response = requests.get(url=CHARGE_URL)
    print(response.status_code)
    if response.status_code == 200:
        data = json.loads(response.content)
        print(data)

def get_power(robotCode): 
    global go_charge_count 
    # 请求数据  
    response = requests.get(STATUS_URL)  
    result = response.json()  
    print(result)
    data = json.loads(response.content)
    charge_state = data['charge_state']
    power_percent = data['power_percent']
    current_pose = data['current_pose']
    go_charge_count = go_charge_count + 1
    if go_charge_count %100 == 0:
        if not isCharging and batteryPercentage<=30:
            go_charge()
    if go_charge_count > 9999:
        go_charge_count=0
    return result  

def get_data(robotCode):  
    response = requests.get(STATUS_URL)  
    result = response.json()  
    print(result)
    data = json.loads(response.content)
    status = data['status']
    payload = dict()
    if status == "OK":
        results = data['results']
        charge_state = results['charge_state']
        power_percent = results['power_percent']
        current_pose = results['current_pose']
        payload['agvCode']=str(robotCode)
        positionStatus={}
        positionStatus['pos_x']=current_pose['x']
        positionStatus['pos_y']=current_pose['y']
        positionStatus['pos_angle']=current_pose['theta']
        payload['positionStatus']=positionStatus
    return payload 

def get_health(robotCode):  
    # 请求数据  
    response = requests.get(health_url)  
    result = response.json()  
    print(result)
    data = dict()
    data['agvCode']=str(robotCode)
    data['info']=result
    return data  
  
def publish_to_mqtt(topic,robotCode,data):  
    # MQTT发布  
    client = mqtt.Client(client_id)  
    client.connect(mqtt_server, mqtt_port)  
    print("topic=["+topic+"]")
    client.publish(topic, json.dumps(data))  
    client.disconnect() 

def get_ip_address(family=2, interface='eth0'):  # family=2 for IPv4, family=10 for IPv6  
    for iface, sniff in psutil.net_if_addrs().items():  
        if iface == interface:  
            for item in sniff:  
                if item.family == family:  
                    return item.address  
    return None  

def get_mac_address(interface='eth0'):
    try:
        command = 'ip link show {} | grep "link/ether "'.format(interface)
        output = os.popen(command).read()
        lines = output.split('\n')

        for line in lines:
            if 'link/ether' in line:
                mac_address = line.split()[1]
                return mac_address
    except Exception as e:
        print("Error:", e)
        return None  


def getUUID():
    mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:].upper()
    mac_address = '-'.join([mac_address[i:i+2] for i in range(0, 11, 2)])
    # 使用默认的接口enp1s0获取IP地址
    ip_address = get_ip_address()
    # ip_address = "192.168.11.148"
    print("IP Address:", ip_address)
    # 使用默认的接口enp1s0获取MAC地址
    mac_address = get_mac_address()
    # mac_address = "48:b0:2d:d3:e5:79"
    print("MAC Address:", mac_address)
    while True:
        param = {"robotIp":ip_address,"robotMac":mac_address,"robotType":"2"}
        response = requests.get(UUID_URL,params=param)
        if response.status_code == 200:
            data = json.loads(response.content)
            print(data)
            robotCode = data['data']['robotCode']
            if robotCode!='unbind' and robotCode!='':
                print("bind success!!!")
                print(str(data)+"=bind success")
                # self.car_id = data['data']['robotId']
                # self.robotCode = data['data']['robotCode']
                return robotCode
        
        time.sleep(1)
        

def getPose(robotCode):
    while True:  
        try:
            data = get_data(robotCode)
            topic = "/robot/"+str(robotCode)+"/position"  
            publish_to_mqtt(topic,robotCode,data)  
        except Exception as e:
            print("Error:", str(e))
            
        time.sleep(1) # 每秒执行一次

robotCode = getUUID()
getPose(robotCode)

